package com.ssyan.boot.handler;

import com.ssyan.boot.entity.User;
import com.ssyan.boot.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author ssyan
 * @Description 函数式处理层 -- Handler层 -- 请求响应：ServerResponse 和 ServerRequest
 * @create 2021/8/17 20:37
 * @Version 1.0
 */
public class UserHandler {

    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    //根据id查询
    public Mono<ServerResponse> getUserById(ServerRequest request) {
        //获取id
        Integer userId = Integer.valueOf(request.pathVariable("id"));

        //创建空值处理对象
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();

        //调用service方法得到数据
        Mono<User> userMono = this.userService.getUserById(userId);
        //把userMono进行转换返回
        //使用Reactor操作符flatMap
        return userMono.flatMap(
                person -> ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromObject(person))
                        .switchIfEmpty(notFound)
        );
    }

    //查询所有
    public Mono<ServerResponse> getAllUsers(ServerRequest request) {
        //调用service得到结果
        Flux<User> users = this.userService.getAllUser();

        //创建空值处理对象
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();

        return ServerResponse.ok().
                contentType(MediaType.APPLICATION_JSON)
                .body(users,User.class)
                .switchIfEmpty(notFound);
    }

    //添加
    public Mono<ServerResponse> saveUser(ServerRequest request) {

        //获取user对象
        Mono<User> userMono = request.bodyToMono(User.class);

        //创建空值处理对象
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();

        return ServerResponse.ok().
                build(this.userService.addUser(userMono))
                .switchIfEmpty(notFound);


    }


}
